/* Copyright (c) 2008, 2009, 2010, 2011 Damian Kmiecik
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   * Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
   * Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in
     the documentation and/or other materials provided with the
     distribution.
   * Neither the name of the copyright holders nor the names of
     contributors may be used to endorse or promote products derived
     from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  POSSIBILITY OF SUCH DAMAGE. */

#include <string.h>
#include <stdlib.h>
#include <inttypes.h>
#include <avr/pgmspace.h>
#include <stdio.h>
#include "config.h"
#include "main.h"
#include "stdout.h"
#include "timer.h"
#include "ethernet.h"
#include "clock.h"
#include "enc28j60.h"
#include "dhcpc.h"

#ifndef	DHCPC_DEBUG
	#define DHCPC_DEBUG(...)
#endif

#ifdef USE_DHCPC

uint32_t dhcpc_lease;
uint8_t dhcpc_state;
struct DHCPC_CACHE dhcpc_cache;

void dhcpcInit(void)
{
	dhcpc_state = DHCP_STATE_IDLE;
	//UDPlisten(DHCP_CLIENT_PORT);
}

uint8_t dhcpc(void)
{
	struct timer_item_s dhcpc_timer;
	uint8_t timeout_cnt = 0;

	timerSet_ms(&dhcpc_timer, 2000);

	if ((dhcpc_state == DHCP_STATE_FINISHED) &&
			(dhcpc_lease < 600))
	{
		dhcpc_state = DHCP_STATE_SEND_REQUEST;
	}

	do
	{
		if (timeout_cnt > 10)
		{
			dhcpc_state = DHCP_STATE_ERR;
			DHCPC_DEBUG("DHCP timeout\n", NULL);
			return 0;
		}

		switch (dhcpc_state)
		{
		case DHCP_STATE_IDLE:
			dhcpcPacket(DHCPDISCOVER);
			timerReset(&dhcpc_timer);
			break;
		case DHCP_STATE_DISCOVER_SENT:
			if (timerExpired(&dhcpc_timer))
			{
				LED_RED_PORT ^= _BV(LED_RED_PIN);
				dhcpc_state = DHCP_STATE_IDLE;
				timeout_cnt++;
			}
			break;
		case DHCP_STATE_OFFER_RCVD:
			timeout_cnt = 0;
			dhcpc_state = DHCP_STATE_SEND_REQUEST;
			break;
		case DHCP_STATE_SEND_REQUEST:
			timerReset(&dhcpc_timer);
			dhcpc_state = DHCP_STATE_REQUEST_SENT;
			dhcpcPacket(DHCPREQUEST);
			break;
		case DHCP_STATE_REQUEST_SENT:
			if (timerExpired(&dhcpc_timer))
			{
				dhcpc_state = DHCP_STATE_SEND_REQUEST;
				timeout_cnt++;
			}
			break;
		case DHCP_STATE_ACK_RCVD:
			DHCPC_DEBUG("LEASE %2x%2x%2x%2x\n", dhcpc_cache.lease[0],dhcpc_cache.lease[1],dhcpc_cache.lease[2],dhcpc_cache.lease[3]);

			dhcpc_lease = (uint32_t)dhcpc_cache.lease[0] << 24 | (uint32_t)dhcpc_cache.lease[1] << 16 | (uint32_t)dhcpc_cache.lease[2] <<  8 | (uint32_t)dhcpc_cache.lease[3];

			settings.mask = *((uint32_t*)&dhcpc_cache.netmask[0]);
			settings.gate = *((uint32_t*)&dhcpc_cache.router_ip[0]);
			#if USE_DNS
			settings.dns = (*((uint32_t*)&dhcpc_cache.dns1_ip[0]));
			#endif
			dhcpc_state = DHCP_STATE_FINISHED;
			break;
		case DHCP_STATE_NAK_RCVD:
			dhcpc_state = DHCP_STATE_IDLE;
			break;
		}
		// If data present
		if (NETCARD_INT)
		{
			uint16_t length = enc28j60ReceivePacket(MTU_SIZE, ethBuffer);
			if (length > 0)
				if (ip->protocol == IP_PROTOCOL_UDP)
					if (udp->destPort == DHCP_CLIENT_PORT)
						dhcpcGet();
		}
	} while (dhcpc_state != DHCP_STATE_FINISHED);
	return 1;
}

void dhcpcPacket(uint8_t type)
{
	struct DHCP_HEADER *msg;
	uint8_t *options;

	for (uint16_t i = 0; i < sizeof(struct DHCP_HEADER); i++)
	{
		ethBuffer[UDP_DATA+i] = 0;
	}

	msg = (struct DHCP_HEADER*)&ethBuffer[UDP_DATA];
	msg->op = 1;
	msg->htype = 1;
	msg->hlen = 6;
	msg->xid[0] = settings.mac[5];
	msg->xid[1] = settings.mac[4];
	msg->xid[2] = settings.mac[3];
	msg->xid[3] = settings.mac[2];
	msg->flags = HTONS(0x8000);
	msg->chaddr[0] = settings.mac[0];
	msg->chaddr[1] = settings.mac[1];
	msg->chaddr[2] = settings.mac[2];
	msg->chaddr[3] = settings.mac[3];
	msg->chaddr[4] = settings.mac[4];
	msg->chaddr[5] = settings.mac[5];

	options = &msg->options[0];
	*options++ = 99;
	*options++ = 130;
	*options++ = 83;
	*options++ = 99;

	*options++ = 53;
	*options++ = 1;
	*options++ = type;

	*options++ = 55;
	*options++ = 3;
	*options++ = 1;
	*options++ = 3;
	*options++ = 6;

	*options++ = 50;
	*options++ = 4;
	*options++ = ((uint8_t*)&(settings.ip))[0];
	*options++ = ((uint8_t*)&(settings.ip))[1];
	*options++ = ((uint8_t*)&(settings.ip))[2];
	*options++ = ((uint8_t*)&(settings.ip))[3];

	*options++ = 61;
	*options++ = 6;
	*options++ = settings.mac[0];
	*options++ = settings.mac[1];
	*options++ = settings.mac[2];
	*options++ = settings.mac[3];
	*options++ = settings.mac[4];
	*options++ = settings.mac[5];

	switch (type)
	{
	case DHCPDISCOVER:
		dhcpc_state = DHCP_STATE_DISCOVER_SENT;
		DHCPC_DEBUG("DISCOVER sent\n", NULL);
		break;
	case DHCPREQUEST:
		*options++ = 54;
		*options++ = 4;
		*options++ = dhcpc_cache.serv_id[0];
		*options++ = dhcpc_cache.serv_id[1];
		*options++ = dhcpc_cache.serv_id[2];
		*options++ = dhcpc_cache.serv_id[3];
		dhcpc_state = DHCP_STATE_REQUEST_SENT;
		DHCPC_DEBUG("REQUEST sent\n", NULL);
		break;
	default:
		DHCPC_DEBUG("Wrong DHCP msg type\n", NULL);
		break;
	}

	*options++ = 12;
	*options++ = 6;
	*options++ = 'A';
	*options++ = 'v';
	*options++ = 'r';
	*options++ = 'E';
	*options++ = 't';
	*options++ = 'h';
	*options = 0xff;

	UDPmakeNewPacket(sizeof(struct DHCP_HEADER), DHCP_CLIENT_PORT, DHCP_SERVER_PORT, (uint32_t)0xffffffff);
}

void get4bytes(uint8_t *source, uint8_t *target)
{
	uint8_t i;
	for (i = 0; i < 4; i++)
	{
	  *target++ = *source++;
	}
}

void dhcpcParseOptions(uint8_t *msg, struct DHCPC_CACHE *c, uint16_t size)
{
	uint16_t ix;
	ix = 0;
	do
	{
		switch (msg[ix])
		{
		case 0: //Padding
			ix++;
			break;
		case 1: //Netmask
			ix++;
			if (msg[ix] == 4)
			{
				ix++;
				get4bytes(&msg[ix], &c->netmask[0]);
				ix += 4;
			} else {
				ix += (msg[ix]+1);
			}
			break;
		case 3: //router (gateway IP)
			ix++;
			if ( msg[ix] == 4 )
			{
				ix++;
				get4bytes(&msg[ix], &c->router_ip[0]);
				ix += 4;
			} else {
				ix += (msg[ix]+1);
			}
			break;
		case 6: //dns len = n * 4
			ix++;
			if (msg[ix] == 4)
			{
				ix++;
				get4bytes(&msg[ix], &c->dns1_ip[0]);
				ix += 4;
			} else
				if (msg[ix] == 8)
				{
					ix++;
					get4bytes(&msg[ix], &c->dns1_ip[0]);
					ix += 4;
//					get4bytes(&msg[ix], &c->dns2_ip[0]);
					ix += 4;
				} else {
					ix += (msg[ix]+1);
				}
			break;
		case 51: //lease time
			ix++;
			if (msg[ix] == 4)
			{
				ix++;
				get4bytes(&msg[ix], &c->lease[0]);
				ix += 4;
			} else {
				ix += msg[ix]+1;
			}
			break;
		case 52: //Options overload
			ix++;
			if (msg[ix] == 1)   //size == 1
			{
				ix++;
				c->ovld = msg[ix];
				ix++;
			} else {
				ix += (msg[ix]+1);
			}
			break;
		case 53: //DHCP Type
			ix++;
			if (msg[ix] == 1)   //size == 1
			{
				ix++;
				c->type = msg[ix];
				ix++;
			} else {
				ix += (msg[ix]+1);
			}
			break;
		case 54: //Server identifier
			ix++;
			if (msg[ix] == 4)
			{
				ix++;
				get4bytes(&msg[ix], &c->serv_id[0]);
				ix += 4;
			} else {
				ix += msg[ix]+1;
			}
			break;
		case 99:   //Magic cookie
			ix += 4;
			break;
		case 0xff: //end option
			break;
		default:
			DHCPC_DEBUG("Unknown Option: %2x\n", msg[ix]);
			ix++;
			ix += (msg[ix]+1);
			break;
		}
	} while ((msg[ix] != 0xff) && (ix < size));
}

void dhcpcGet(void)
{
	struct DHCP_HEADER *msg;
	uint8_t *p;
	uint16_t i;

	if (htons(ip->totalLen) > MTU_SIZE)
	{
		DHCPC_DEBUG("DHCP too big, discarded\n", NULL);
		return;
	}

	p = &dhcpc_cache.type; //clear the dhcpc_cache
	for (i=0; i < sizeof(dhcpc_cache); i++)
	{
		p[i] = 0;
	}

	// set pointer of DHCP message to beginning of UDP data
	msg = (struct DHCP_HEADER*)&ethBuffer[UDP_DATA];

	//check the id
	if ((msg->xid[0] != settings.mac[5]) || (msg->xid[1] != settings.mac[4]) || (msg->xid[2] != settings.mac[3]) || (msg->xid[3] != settings.mac[2]))
	{
		DHCPC_DEBUG("Wrong DHCP ID, discarded\n", NULL);
		return;
	}

	dhcpcParseOptions(&msg->options[0], &dhcpc_cache, (htons(ip->totalLen)-264) );
	// check if file field or sname field are overloaded (option 52)
	switch (dhcpc_cache.ovld)
	{
	case 0:  // no overload, do nothing
		break;
	case 1:  // the file field contains options
		dhcpcParseOptions(&msg->file[0], &dhcpc_cache, 128);
		break;
	case 2:  // the sname field contains options
		dhcpcParseOptions(&msg->sname[0], &dhcpc_cache, 64);
		break;
	case 3:  // the file and the sname field contain options
		dhcpcParseOptions(&msg->file[0], &dhcpc_cache, 128);
		dhcpcParseOptions(&msg->sname[0], &dhcpc_cache, 64);
		break;
	default: // must not occur
		DHCPC_DEBUG("Option 52 Error\n", NULL);
		break;
	}

	switch (dhcpc_cache.type)
	{
	case DHCPOFFER:
		// this will be our IP address
		settings.ip = *((uint32_t*)&msg->yiaddr[0]);
		DHCPC_DEBUG("** DHCP OFFER RECVD! **\n", NULL);
		dhcpc_state = DHCP_STATE_OFFER_RCVD;
		break;
	case DHCPACK:
		DHCPC_DEBUG("** DHCP ACK RECVD! **\n", NULL);
		dhcpc_state = DHCP_STATE_ACK_RCVD;
		break;
	case DHCPNAK:
		DHCPC_DEBUG("** DHCP NAK RECVD! **\n", NULL);
		dhcpc_state = DHCP_STATE_NAK_RCVD;
		break;
	}
}

#endif
